package com.game.service;

import java.time.LocalDateTime;
import java.util.UUID;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.game.entity.UserSession;
import com.game.exception.BusinessException;
import com.game.repository.UserSessionRepository;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class SessionService {
    private final UserSessionRepository userSessionRepository;
    private static final long SESSION_EXPIRE_HOURS = 24;

    public String createSession(Long userId) {
        String token = UUID.randomUUID().toString();
        UserSession session = new UserSession();
        session.setUserId(userId);
        session.setToken(token);
        session.setExpireTime(LocalDateTime.now().plusHours(SESSION_EXPIRE_HOURS));
        userSessionRepository.save(session);
        return token;
    }

    public Long getUserId(String token) {
        UserSession session = userSessionRepository.findByToken(token)
            .orElseThrow(() -> new BusinessException("未登录或登录已过期"));
            
        if (session.getExpireTime().isBefore(LocalDateTime.now())) {
            userSessionRepository.delete(session);
            throw new BusinessException("登录已过期");
        }
        
        return session.getUserId();
    }

    @Transactional
    public void removeSession(String token) {
        userSessionRepository.deleteByToken(token);
    }

    @Transactional
    public void cleanExpiredSessions() {
        userSessionRepository.deleteExpiredSessions(LocalDateTime.now());
    }
} 